package chu.dejian.ui.unused;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import com.sam.ble.unimplements.BLEBRHelper;
import com.sam.blemodule.R;
import chu.dejian.conf.BLEPreference;
import chu.dejian.db.DBHelper;
import chu.dejian.entity.RecordEntity;
import chu.dejian.models.GetMeasurementResponse;
import chu.dejian.restApi.RestClient;
import com.sam.ui.base.fragment.BaseFragment;
import com.sam.utils.L;
import com.sam.utils.T;

import chu.dejian.ui.fragmet.RecordChartFragment;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class RecordHistoryFragment extends BaseFragment {
	private static RecordHistoryFragment instance;
	public synchronized static RecordHistoryFragment getInstance(){
		if(instance == null){
			instance = new RecordHistoryFragment();
		}
		return instance;
	}

	private View timeLeftBtn,timeRightBtn,speekerBtn, checkChartBtn;
	private TextView recordTime,sysValueTV,diaValueTV,pulValueTV, pulseStateTV, messageTV;
	private int currentRecordIndex = -1;
	List<RecordEntity> recordEntityList;
	private AnsyncMeasureRecordThread ansyncMeasureRecordThread = new AnsyncMeasureRecordThread();

	private static final int SHOW_RECORD = 0;
	private static final int ALERT_MESSAGE = 1;

	private Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what){
				case SHOW_RECORD:
					showRecord((int)msg.obj);
					break;
				case ALERT_MESSAGE:
					T.showLong(getActivity(),(String)msg.obj);
					break;
			}
			super.handleMessage(msg);
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_measure_history);
	}

	@Override
	public void findView() {
		timeLeftBtn = findViewById(R.id.select_left_record);
		timeRightBtn = findViewById(R.id.select_right_record);
		recordTime = (TextView) findViewById(R.id.record_time);
		sysValueTV = (TextView) findViewById(R.id.shrinkage_value);
		diaValueTV = (TextView) findViewById(R.id.diastolic_value);
		pulValueTV = (TextView) findViewById(R.id.pulse_value);
		pulseStateTV = (TextView) findViewById(R.id.boold_pressure);
		messageTV = (TextView) findViewById(R.id.diagnostic_criteria);
		speekerBtn = findViewById(R.id.diagnostic_criteria_speaker);
		checkChartBtn = findViewById(R.id.check_analysis_chart);
	}

	@Override
	public void initView() {
		timeLeftBtn.setOnClickListener(onClickListener);
		timeRightBtn.setOnClickListener(onClickListener);
		speekerBtn.setOnClickListener(onClickListener);
		checkChartBtn.setOnClickListener(onClickListener);
		recordEntityList = DBHelper.getInstance().getRecordDao().getAllRecord();
		if(recordEntityList == null || recordEntityList.size() == 0) return;
		showRecord(recordEntityList.size() - 1);
	}

	@Override
	public void onResume() {
		super.onResume();
		ansyncMeasureRecordThread.start();
	}

	private boolean isAnsyncRecord = false;
	private void ansyncMeasureRecord(){
		if(isAnsyncRecord) return;
		isAnsyncRecord = true;
//		final String fromTime = AppPreference.getInstance().getLastRecordCheckTimeStamp()/1000L+"";
//		final String toTime = System.currentTimeMillis()/1000L+"";
		final int page = BLEPreference.getInstance().getMeasurementPage();
		RestClient.getAuthedClient().getApiService().getMeasurement(page, new Callback<GetMeasurementResponse>(){

			@Override
			public void success(GetMeasurementResponse getMeasurementResponse, Response response) {
				if(response.getStatus() == 401) {
					BLEBRHelper.getInstance().sendReloginBR(getActivity());
					T.showShort(getActivity(),R.string.nauthorized_and_relogin);
					return;
				}
				L.d("《获取测量记录-getMeasurement》" + "\n" + "请求成功： \n\t返回数据：" + getMeasurementResponse.toString());
				List<GetMeasurementResponse.ResultsEntity> recordEntities = getMeasurementResponse.getResults();
				if(recordEntities == null || recordEntities.size() == 0) return;
				List<RecordEntity> res = new ArrayList<RecordEntity>();
				for(GetMeasurementResponse.ResultsEntity recordEntity : recordEntities){
					GetMeasurementResponse.ResultsEntity.ResultEntity measurement = recordEntity.getResult();
					if(measurement != null && measurement.getSystolic() != 0 && measurement.getDiastolic() != 0 && measurement.getPulse() != 0){
						RecordEntity re = new RecordEntity(measurement.getSystolic(),measurement.getDiastolic(),measurement.getPulse(),recordEntity.getTime());
						re.pulseState = measurement.getPulsestate();
						re.message = measurement.getMessage();
						re.note = measurement.getNote();
						res.add(re);
					}
				}
				res.removeAll(recordEntityList);  // 移除已经存储过的记录
				for(RecordEntity re : res){
					DBHelper.getInstance().getRecordDao().insertRecord(re);
				}
				recordEntityList.addAll(res);
				isAnsyncRecord = false;
				if(getMeasurementResponse.getNext() != null && !getMeasurementResponse.getNext().equals("null")){
					BLEPreference.getInstance().setMeasurementPage(page+1);
					ansyncMeasureRecord();
				} else if(recordEntityList.size() > 0) {
					Message msg = new Message();
					msg.what = SHOW_RECORD;
					msg.obj = recordEntityList.size() - 1;
					handler.sendMessage(msg);
				}
			}

			@Override
			public void failure(RetrofitError retrofitError) {
				L.d("《获取测量记录-getMeasurement》"+"\n"+ "请求失败： \n\t错误信息：" + retrofitError.toString());
//				T.showLong(getActivity(),R.string.measure_record_ansync_failed);
				Message msg = new Message();
				msg.what = ALERT_MESSAGE;
				msg.obj = getResources().getString(R.string.measure_record_ansync_failed);
				handler.sendMessage(msg);
				isAnsyncRecord = false;
			}
		});
	}

	private void showRecord(int recordIndex){
		if(currentRecordIndex == recordIndex) return;
		try{
			RecordEntity recordEntity = recordEntityList.get(recordIndex);
			SimpleDateFormat sdf = new SimpleDateFormat(getResources().getString(R.string.message_time_format));
			recordTime.setText(sdf.format(recordEntity.getMeasureDateTime()));
			sysValueTV.setText(recordEntity.systolic+"");
			diaValueTV.setText(recordEntity.diastolic+"");
			pulValueTV.setText(recordEntity.pulse+"");
			pulseStateTV.setText(R.string.rhythm);
			if(recordEntity.pulseState == 0){
				pulseStateTV.append(getResources().getText(R.string.normal));
			} else if(recordEntity.pulseState == 1){
				pulseStateTV.append(getResources().getText(R.string.arrhythmia));
			} else {
				pulseStateTV.setText(recordEntity.pulseState);
			}
			messageTV.setText(recordEntity.message);
		} catch (Exception exceptipn){
			L.d("显示历史记录时发生异常："+exceptipn.toString() + " recordIndex = "+  recordIndex +
					" currentRecordIndex = "+currentRecordIndex+" recordEntityList.size()"+recordEntityList.size());
			recordTime.setText(R.string.no_data);
			sysValueTV.setText("-");
			diaValueTV.setText("-");
			pulValueTV.setText("-");
			pulseStateTV.setText("-");
			messageTV.setText("-");
		}
		currentRecordIndex = recordIndex;
		checkArrowState();
	}

	private void checkArrowState(){
		if(recordEntityList.size() < 2) {
			timeLeftBtn.setVisibility(View.INVISIBLE);
			timeRightBtn.setVisibility(View.INVISIBLE);
		} else {
			timeLeftBtn.setVisibility(View.VISIBLE);
			timeRightBtn.setVisibility(View.VISIBLE);
			if(currentRecordIndex == 0) {
				timeLeftBtn.setVisibility(View.INVISIBLE);
			}
			if(currentRecordIndex == recordEntityList.size() - 1){
				timeRightBtn.setVisibility(View.INVISIBLE);
			}
		}

	}

	private View.OnClickListener onClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			int i = v.getId();
			if (i == R.id.select_left_record) {
				showRecord(currentRecordIndex - 1 < 0 ? 0 : currentRecordIndex - 1);

			} else if (i == R.id.select_right_record) {
				showRecord(currentRecordIndex + 1 >= recordEntityList.size() ? recordEntityList.size() - 1 : currentRecordIndex + 1);

			} else if (i == R.id.diagnostic_criteria_speaker) {
			} else if (i == R.id.check_analysis_chart) {
				replaceSelfWithFragment(RecordChartFragment.getInstance());

			}
		}
	};

	class AnsyncMeasureRecordThread implements Runnable {
		public boolean running = false;
		private Thread thread = null;

		public void run() {
			ansyncMeasureRecord();
		}

		public void start() {
			try {
				this.thread = new Thread(this);
				this.running = true;
				this.thread.start();
			} finally {
			}
		}

		public void stop() {
			try {
				this.running = false;
				this.thread = null;
			} finally {
			}
		}
	}
}
